package com.css.fxfzypg.base.dict.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.cache.CacheService;
import com.css.fxfzypg.base.dict.repository.DictRepository;
import com.css.fxfzypg.base.dict.repository.DictItemRepository;
import com.css.fxfzypg.base.dict.service.DictService;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.base.dict.repository.DictDirectoryRepository;
import com.css.fxfzypg.base.dict.repository.entity.DictDirectoryEntity;
import com.css.fxfzypg.base.dict.repository.entity.DictEntity;
import com.css.fxfzypg.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzypg.base.dict.service.DictDirectoryService;
import com.css.fxfzypg.base.dict.viewobjects.DictDirectoryQueryParams;
import com.css.fxfzypg.base.dict.viewobjects.DictDirectoryVO;
import com.css.fxfzypg.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import static com.css.fxfzypg.constants.FxfzConstants.CACHE_SYS_KEY;

@Service
@Slf4j
public class DictDirectoryImpl implements DictDirectoryService {
    @Autowired
    DictDirectoryRepository dictDirectoryRepository;
    @Autowired
    DictService dictService;
    @Autowired
    DictItemRepository dictItemRepository;
    @Autowired
    DictRepository dictRepository;
    @Autowired
    CacheService cacheService;

    private static final String CACHE_DICT_ID_KEY = "dictId:";
    private static final String CACHE_DICT_CODE_KEY = "dictCode:";
    private static final String CACHE_DICT_CODE_LIST_KEY = "dictCodeList:";
    private static final String CACHE_DICT_ITEM_ID_KEY = "dictItemId:";
    private static final String CACHE_DICT_ITEM_CODE_KEY = "dictItemCode:";

    @Override
    public JSONObject queryDictDirectorys(DictDirectoryQueryParams queryParams, int curPage, int pageSize) {
        Page<DictDirectoryEntity> dictDirectoryEntities = dictDirectoryRepository.queryDictDirectorys(queryParams,curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(dictDirectoryEntities);
        return jsonObject;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DictDirectoryEntity saveDictDirectory(DictDirectoryEntity directoryEntity) {
        String uuid = UUIDGenerator.getUUID();
        directoryEntity.setDictDirId(uuid);
        directoryEntity.setCreateUser(PlatformSessionUtils.getUserId());
        directoryEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        String parentId = directoryEntity.getParentId();
        if ("".equals(parentId)) {
            directoryEntity.setAllParentId(uuid);
        } else {
            DictDirectoryEntity dtEntity = dictDirectoryRepository.findById(parentId);
            directoryEntity.setAllParentId(dtEntity.getAllParentId() + FxfzConstants.STR_SEPARATOR + uuid);
        }
        dictDirectoryRepository.save(directoryEntity);
        return directoryEntity;
    }

    @Override
    public DictDirectoryEntity updateDictDirectory(DictDirectoryEntity directoryEntity) {
        directoryEntity.setUpdateUser(PlatformSessionUtils.getUserId());
        directoryEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        dictDirectoryRepository.save(directoryEntity);
        return directoryEntity;
    }

    @Override
    public DictDirectoryVO getDictDirectory(String id) {
        DictDirectoryEntity directoryEntity = dictDirectoryRepository.findById(id);
        DictDirectoryVO dictDirectoryVO = new DictDirectoryVO();
        if (PlatformObjectUtils.isNotEmpty(directoryEntity)) {
            log.info(directoryEntity.toString());
            BeanUtils.copyProperties(directoryEntity,dictDirectoryVO);
            if(PlatformObjectUtils.isNotEmpty(dictDirectoryVO.getAdminRoleId())){
                //todo 从平台拿RoleEntity
                //String roleName = PlatformAPI.getOrgAPI().getRoleAPI().getRole(dictDirectoryVO.getAdminRoleId());
                //dictDirectoryVO.setAdminRoleName(roleName);
            }
            return dictDirectoryVO;
        } else {
            return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDictDirectorys(List<String> ids) {
        deleteDictAndItemCache(ids);
        List<String> dictIds = new ArrayList<>();
        for (String id : ids) {
            List<String> dictId = dictService.getDictIdsByDictDirId(id);
            if (dictId != null && dictId.size() > 0) {
                dictIds.addAll(dictId);
            }
            if(PlatformObjectUtils.isNotEmpty(dictIds)){
                dictService.deleteDicts(dictIds);
            }
            dictDirectoryRepository.deleteByAllParentIdContaining(id.trim());
        }
    }

    private void deleteDictAndItemCache(List<String> ids) {
        List<String> dictCacheKeys = new ArrayList<String>();
        List<DictEntity> dicts = dictRepository.findAllByDirId(ids);
        List<DictItemEntity> dictItems = dictItemRepository.findDictItemByDictDirId(ids);
        if (PlatformObjectUtils.isNotEmpty(dicts)) {
            for (DictEntity dict : dicts) {
                dictCacheKeys.add(CACHE_SYS_KEY + CACHE_DICT_ID_KEY + dict.getDictId());
                dictCacheKeys.add(CACHE_SYS_KEY + CACHE_DICT_CODE_KEY + dict.getDictCode());
                dictCacheKeys.add(CACHE_SYS_KEY + CACHE_DICT_CODE_LIST_KEY + dict.getDictCode());
            }
        }
        if (PlatformObjectUtils.isNotEmpty(dictItems)) {
            for (DictItemEntity dictItem : dictItems) {
                dictCacheKeys.add(CACHE_SYS_KEY + CACHE_DICT_ITEM_ID_KEY + dictItem.getDictItemId());
                dictCacheKeys.add(CACHE_SYS_KEY + CACHE_DICT_ITEM_CODE_KEY + dictItem.getDictItemCode());
            }
        }
        cacheService.delete(dictCacheKeys);
    }

    @Override
    public boolean validateDictDirCode(String dictDirId, String dictDirCode) {
        boolean isValid = false;
        DictDirectoryEntity de = dictDirectoryRepository.findOneByDictDirCode(dictDirCode);
        if (PlatformObjectUtils.isEmpty(de)) {
            isValid = false;
        } else if (de.getDictDirId().equals(dictDirId)) {
            isValid = true;
        }
        return isValid;
    }

    @Override
    public List<DictDirectoryEntity> initDictDirZtree() {

        List<DictDirectoryEntity> list = new ArrayList<>();
        String userId = PlatformSessionUtils.getUserId();
        //todo
        //boolean isSuperAdmin = PlatformAPI.getOrgAPI().getUserAPI().isSuperAdmin(userId);
        boolean isSuperAdmin =true;
        if(isSuperAdmin){
            list = dictDirectoryRepository.findOrderBySort();
        }else {
            list = this.listQualifiedDirectorysForTree(userId);
        }
        return list;
    }


    private List<DictDirectoryEntity> listQualifiedDirectorysForTree(String userId) {
        String trc = "root";
        DictDirectoryEntity rootDirectory = dictDirectoryRepository.findOneByDictDirCode(trc);
        List<DictDirectoryEntity> directories = this.listQualifiedDirectorys(userId);
        directories.add(rootDirectory);
        return directories;
    }


    private  List<DictDirectoryEntity> listQualifiedDirectorys(String userId){
        List<DictDirectoryEntity> directoryList = new ArrayList();
        //todo
        //List<String> roleIds = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        List<String> roleIds = new ArrayList<>();
        //superadmin的roleIds
        roleIds.add("30e6878ef8ad4701b7e19abe5f1cd5db");
        roleIds.add("f895299310764dcf9c3afec8ce6fb39d");
        roleIds.add("85e1884f4a3648a8a02b0b95b5b79a2d");
        if (PlatformObjectUtils.isNotEmpty(roleIds)) {
             directoryList = dictDirectoryRepository.findDirectorysByRoles(roleIds);
        }
        return directoryList;
    }
}
